import React, { useState } from 'react';
import {
  Button,
  Col,
  Form,
  Input,
  Row,
  Table,
  Popconfirm,
  Card,
  message,
  Select,
  DatePicker,
} from 'antd';
import { useAntdTable, useRequest } from 'ahooks';

import { IAntdTablePageParams } from '@/types/type';
import { PlusOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import LogModal from './logModal';
import { Moment } from 'moment';
import {
  drivingLogContinuation,
  drivingLogEndTask,
  drivingLogList,
  getCurrentBrand,
} from '@/services/intelligentDrivingLog/intelligentDrivingLogList';
import {
  DrivingLogListItem,
  DrivingLogListParams,
} from '@/types/intelligentDrivingLog/intelligentDrivingLogList.d';
import { ColumnsType } from 'antd/es/table';

enum OperationEnum {
  ADD = 'add',
  EDIT = 'edit',
  CLOSE = 'close',
}

const { RangePicker } = DatePicker;

const logTypeOptions = [
  { label: 'Syslog', value: 1 },
  { label: 'Otherlog', value: 2 },
  { label: 'EDR', value: 3 },
  { label: 'DSSAD', value: 4 },
  { label: 'Reserved', value: 5 },
];

const taskStatusOptions = [
  { label: '等待执行', value: 0 },
  { label: '执行中', value: 1 },
  { label: '结束', value: 2 },
  { label: '执行失败', value: 3 },
];

const fileStatusOptions = [
  { label: '等待上传', value: 0 },
  { label: '上传中', value: 1 },
  { label: '上传成功', value: 2 },
  { label: '上传失败', value: 3 },
];

enum FileStatusEnum {
  Pedding = 0,
  Uploading = 1,
  Success = 2,
  Fail = 3,
}

const StatusColorMap = new Map([
  [0, '#faad14'],
  [1, '#faad14'],
  [2, '#52c41a'],
  [3, '#ff4d4f'],
]);

const getTableData = async (
  { current, pageSize }: IAntdTablePageParams,
  formData: Omit<DrivingLogListParams, 'page' | 'size'>,
) => {
  let { date, ...rest } = formData as any;
  let params: DrivingLogListParams = { page: current, size: pageSize, ...rest };
  if (date) {
    let [startDate, endDate] = date;
    params.startDate = dayjs(startDate).format('YYYY-MM-DD HH:mm:ss');
    params.endDate = dayjs(endDate).format('YYYY-MM-DD HH:mm:ss');
  }
  let { data } = await drivingLogList(params);

  return {
    total: data.pagination.total,
    list: data.list || [],
  };
};

const Index = () => {
  const [open, setOpen] = useState(OperationEnum.CLOSE);
  const [form] = Form.useForm();
  const [dates, setDates] = useState<any>(null);
  const { tableProps, search, params } = useAntdTable(getTableData, {
    defaultPageSize: 10,
    form,
  });
  const { submit, reset } = search;
  const { current, pageSize } = params[0] || ({} as any);

  // 品牌下拉列表
  const { data: brandOptions = [], loading: brandLoading } = useRequest(getCurrentBrand);

  const refresh = () => {
    submit();
  };
  const onAdd = () => {
    setOpen(OperationEnum.ADD);
  };

  const onContinuation = async (record: DrivingLogListItem) => {
    let id = record.id as unknown as string;
    let res = await drivingLogContinuation({ id });
    if (res.statusCode === '0') {
      message.success('操作成功');
      refresh();
    }
  };

  const endTask = async (record: DrivingLogListItem) => {
    let id = record.id as unknown as string;
    let res = await drivingLogEndTask({ id });
    if (res.statusCode === '0') {
      message.success('操作成功');
      refresh();
    }
  };

  const onCancel = (options?: { isRefresh?: boolean }) => {
    setOpen(OperationEnum.CLOSE);
    if (options && options.isRefresh) {
      refresh();
    }
  };

  const columns: ColumnsType<DrivingLogListItem> = [
    {
      title: '序号',
      align: 'center',
      width: 70,
      render(_, record, index) {
        return (current - 1) * pageSize + index + 1;
      },
    },
    {
      title: 'VIN',
      dataIndex: 'vin',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '日志类别',
      dataIndex: 'logType',
      align: 'center',
      ellipsis: true,
      render(value) {
        let logTypeArr: string[] = value.split(';');
        let item = logTypeOptions
          .filter(item => logTypeArr.includes(`${item.value}`))
          .map(item => item.label);
        return <span>{item.join(';') || '--'}</span>;
      },
    },
    {
      title: '任务创建时间',
      dataIndex: 'createTime',
      align: 'center',
      render(_, record) {
        const { createTime } = record;
        if (createTime === null || createTime === undefined) {
          return '--';
        }
        return dayjs(createTime).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTime',
      align: 'center',
      width: 100,
      render(_, record) {
        const { uploadTime } = record;
        if (uploadTime === null || uploadTime === undefined) {
          return '--';
        }
        return dayjs(uploadTime).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '任务状态',
      dataIndex: 'taskStatus',
      align: 'center',
      render(value) {
        let item = taskStatusOptions.find(item => item.value === value);
        let color = StatusColorMap.get(value) || '';
        return <span style={{ color: color }}>{item?.label || '--'}</span>;
      },
    },
    {
      title: '文件状态',
      dataIndex: 'fileStatus',
      align: 'center',
      render(value) {
        let item = fileStatusOptions.find(item => item.value === value);
        let color = StatusColorMap.get(value) || '';
        return <span style={{ color: color }}>{item?.label || '--'}</span>;
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      align: 'center',
      fixed: 'right',
      render(_, record) {
        // 续传标识（0:允许；1:禁止）
        let { continuationFlag, fileStatus } = record;
        if (fileStatus === FileStatusEnum.Fail && continuationFlag === 0) {
          return [
            <Popconfirm
              title="你确定要续传吗？"
              onConfirm={() => onContinuation(record)}
              key="delete"
            >
              <Button type={'link'} size="middle">
                续传
              </Button>
            </Popconfirm>,
            <Popconfirm title="你确定要结束任务吗？" onConfirm={() => endTask(record)} key="delete">
              <Button type={'link'} size="middle">
                结束任务
              </Button>
            </Popconfirm>,
          ];
        }
        return;
      },
    },
  ];

  const disabledDate = (current: Moment) => {
    if (!dates) {
      return false;
    }
    const tooLate = dates[0] && current.diff(dates[0], 'days') > 30;
    const tooEarly = dates[1] && dates[1].diff(current, 'days') > 30;
    return !!tooEarly || !!tooLate;
  };

  const onOpenChange = (open: boolean) => {
    if (open) {
      setDates([null, null]);
    } else {
      setDates(null);
    }
  };

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };

  return (
    <Card>
      <Form form={form} {...formItemLayout}>
        <Row gutter={16}>
          <Col span={6} offset={1}>
            <Form.Item label="品牌" name="brandCode">
              <Select
                placeholder="请选择品牌"
                loading={brandLoading}
                options={brandOptions}
                fieldNames={{ label: 'brandName', value: 'brandCode' }}
                allowClear
              />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item label="VIN" name="vin">
              <Input placeholder="请输入VIN" allowClear />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item label="日志类别" name="logType">
              <Select placeholder="请选择日志类别" options={logTypeOptions} allowClear />
            </Form.Item>
          </Col>
          <Col>
            <Button type="primary" onClick={submit} >
              查询
            </Button>
            <Button onClick={reset} style={{ marginLeft: 16 }} >
              重置
            </Button>
          </Col>
          <Col span={7}>
            <Form.Item label="创建时间" name="date">
              <RangePicker
                showTime
                format="YYYY-MM-DD HH:mm:ss"
                disabledDate={disabledDate}
                onCalendarChange={val => setDates(val)}
                onOpenChange={onOpenChange}
              />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item label="任务状态" name="taskStatus">
              <Select placeholder="请选择日志类别" allowClear options={taskStatusOptions} />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item label="文件状态" name="fileStatus">
              <Select placeholder="请选择日志类别" allowClear options={fileStatusOptions} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <div style={{ marginBottom: 16 }}>
        <Button icon={<PlusOutlined />} type="primary" onClick={onAdd} size="middle">
          新建日志
        </Button>
      </div>
      <Table columns={columns} rowKey="id" bordered {...tableProps} scroll={{ x: 'max-content' }} />
      <LogModal
        open={OperationEnum.ADD === open}
        onClose={onCancel}
        logTypeOptions={logTypeOptions}
      />
    </Card>
  );
};

export default Index;
